package com.shitou.shitoumember.utils;

import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * class detail:
 *      根据ip获取地址
 * @author 石头人
 */
@Slf4j
@SuppressWarnings("all")
public class IPToCityUtils {

    public static String iPToCityUtils(String ip){
        // 创建Searcher对象
        String dbPath = "ip2region.xdb";
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            log.error("创建searcher失败 {}: {}\n", dbPath, e);
            return null;
        }

        // 查询
        try{


            long sTime = System.nanoTime();
            // 获得区域
            String region = searcher.search(ip);
            if ( region.equals("0|0|0|内网IP|内网IP")){
                return "内网IP";
                //中国|0|贵州省|黔南|电信
            }
            // 花费时间
            long cost = TimeUnit.NANOSECONDS.toMicros((System.nanoTime() - sTime));
            System.out.println(region);
            region = region.replace("|0|", "-");
            region = region.replace("|", "-");
            log.info("region: {}, ioCount: {}, took: {} μs", region, searcher.getIOCount(), cost);
            searcher.close();
            return region;
        } catch (Exception e){
            log.error("搜索区域失败 {}: {}\n", ip, e);
            return "未知";
        }
    }

    public static void main(String[] args) {
        System.out.println(iPToCityUtils("220.197.4.173"));
        System.out.println(iPToCityUtils("127.0.0.1"));
        String a = "中国|0|贵州省|黔南|电信";
        String b = "中国|0|贵州省|0|联通";
        a = a.replace("|0|", "-");
        a = a.replace("|", "-");
        System.out.println(a);

    }

}
